<?php

class Admin_UserController extends JControllerAdmin
{
    /**
     * @return void
     */
    public function init()
    {
        $layout = Zend_Layout::getMvcInstance();
        $actionName = $this->_request->getActionName();
        switch ($actionName) {
            case 'add':
            case 'update':
                $layout->setLayout('admin/layout-admin-add');
                break;
        }
    }

    /**
     * @return void
     */
    public function indexAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $messages = $flashMessenger->getMessages();
        $this->view->messages = $messages;

        $userTypePOJOs = Application_Model_UserType::getUserTypes(true);
        $this->view->userTypePOJOs = $userTypePOJOs;

        // BEGIN: Tạo đối tượng Paginator
        $dbSelect = JDbAdapter::factory()
            ->select()
            ->from(array('u' => 'USERS'))
            ->join(
                array('ut' => 'USER_TYPES'), 'u.UserTypeID = ut.ID',
                array('UserType' => 'ut.Name')
            );

        // Tìm kiếm theo tên người dùng (nếu có)
        $keyWords = $this->_request->getParam('keyWords');
        if (isset($keyWords)) {
            $dbSelect->where("Username LIKE '%$keyWords%'");
            $this->view->enteredKeyWords = $keyWords;
        }

        // Lọc theo nhóm người dùng
        $userTypeID = $this->_request->getParam('userTypeID');
        if (isset($userTypeID)) {
            $childUserTypeIDs = Application_Model_UserType::getUserTypeGroup($userTypeID);
            $dbSelect->where('UserTypeID IN (?)', $childUserTypeIDs);
            $this->view->selectedUserTypeID = $userTypeID;
        }

        $paginator = new Zend_Paginator(
            new Zend_Paginator_Adapter_DbSelect($dbSelect)
        );
        // END: Tạo đối tượng Paginator

        // Get and set current page
        $page = $this->_request->getParam('page');
        $paginator->setCurrentPageNumber($page);
        $users = $paginator->getItemsByPage($page);

        // Assign data for view
        $this->view->users = $users;
        $this->view->paginator = $paginator;
    }

    /**
     * @return void
     */
    public function addAction()
    {
        $this->view->messages = array();
        $this->view->layout = 'add';

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $username = $this->_request->getParam('username');
            $email = $this->_request->getParam('email');
            $password = $this->_request->getParam('password');
            $realName = $this->_request->getParam('realName');
            $birthday = new Zend_Date($this->_request->getParam('birthday'));
            $mobilePhone = $this->_request->getParam('mobilePhone');
            $userTypeID = $this->_request->getParam('userTypeID');

            // BEGIN: chứng thực User
            $messages = array();
            $validInfo = true;

            $authentication = JAuthentication::getInstance();
            $authentication->setRequiredInfo('Username');
            $result = $authentication->authenticate($username);
            if ($result->getCode() == Zend_Auth_Result::SUCCESS) {
                array_push($messages, 'This Username Existed');
                $validInfo = false;
            }

            $authentication->setRequiredInfo('Email');
            $result = $authentication->authenticate($email);
            if ($result->getCode() == Zend_Auth_Result::SUCCESS) {
                array_push($messages, 'This Email Existed');
                $validInfo = false;
            }
            // END: chứng thực User

            if (!$validInfo) {
                $this->view->messages = $messages;
                $this->view->username = $username;
                $this->view->email = $email;
                $this->view->password = $password;
                $this->view->realName = $realName;
                $this->view->birthday = $birthday->get('d - M - Y');
                $this->view->mobilePhone = $mobilePhone;
                $this->view->selectedUserTypeID = $userTypeID;
            } else {
                $newUserID = Application_Model_User::addUser(
                    $username, $email, $password, $realName,
                    $birthday, $mobilePhone, $userTypeID
                );
                if ($newUserID == 0) {
                    $this->view->messages = array('Add User Fail!!!');
                } else {
                    /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
                    $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                    $task = $this->_request->getParam('task');
                    switch ($task) {
                        case 'apply':
                            $flashMessenger->addMessage('Add User Successfully!!!');
                            $this->redirect("/admin/user/update/userID/$newUserID");
                            break;
                        case 'apply-and-close':
                            $flashMessenger->addMessage('Add User Successfully!!!');
                            $this->redirect('/admin/user/index');
                            break;
                        case 'apply-and-new':
                            $this->view->messages = array('Add User Successfully!!!');
                            break;
                        default:
                            $flashMessenger->addMessage('Cannot Determine Next Task');
                            $this->redirect('/admin/user/index');
                            break;
                    }
                }
            }
        }

        $userTypePOJOs = Application_Model_UserType::getUserTypes(true);
        $this->view->userTypePOJOs = $userTypePOJOs;
    }

    /**
     * @return void
     */
    public function deleteAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/user/index');
        }

        $userIDs = $this->_request->getParam('userIDs');
        if (!Application_Model_User::deleteUsers($userIDs)) {
            $flashMessenger->addMessage('Delete Fail');
        } else {
            $var = '';

            $length = count($userIDs);
            for ($i = 0; $i < $length - 1; $i++) {
                $var .= $userIDs[$i] . ', ';
            }
            $var .= $userIDs[$length - 1];

            $flashMessenger->addMessage("Delete $var Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * @return void
     */
    public function updateAction()
    {
        /** @var Zend_Controller_Action_Helper_FlashMessenger $flashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $messages = $flashMessenger->getMessages();
        $this->view->messages = $messages;
        $this->view->layout = 'update';

        $isPost = $this->_request->getParam('isPost');
        if (isset($isPost)) {
            $id = $this->_request->getParam('userID');
            $username = $this->_request->getParam('username');
            $email = $this->_request->getParam('email');
            $password = $this->_request->getParam('password');
            $realName = $this->_request->getParam('realName');
            $birthDay = new Zend_Date($this->_request->getParam('birthday'));
            $mobilePhone = $this->_request->getParam('mobilePhone');
            $userTypeID = $this->_request->getParam('userTypeID');

            $success = Application_Model_User::updateUser(
                $id, $password, $realName, $birthDay,
                $mobilePhone, $userTypeID
            );
            if (!$success) {
                $this->view->messages = array('Update User Fail');
                $this->view->username = $username;
                $this->view->email = $email;
                $this->view->password = $password;
                $this->view->realName = $realName;
                $this->view->birthday = $birthDay->get('d - M - y');
                $this->view->mobilePhone = $mobilePhone;
                $this->view->selectedUserTypeID = $userTypeID;
            } else {
                $task = $this->_request->getParam('task');
                switch ($task) {
                    case 'apply':
                        $this->view->messages = array('Update User Successfully');
                        $this->view->username = $username;
                        $this->view->email = $email;
                        $this->view->password = $password;
                        $this->view->realName = $realName;
                        $this->view->birthday = $birthDay->get('d - M - y');
                        $this->view->mobilePhone = $mobilePhone;
                        $this->view->selectedUserTypeID = $userTypeID;
                        break;
                    case 'apply-and-close':
                        $flashMessenger->addMessage('Update User Successfully');
                        $this->redirect('/admin/user/index');
                        break;
                    default:
                        $flashMessenger->addMessage('Cannot Determine Next Task');
                        $this->redirect('/admin/user/index');
                        break;
                }
            }
        } else {
            $userID = $this->_request->getParam('userID');
            $userPOJO = Application_Model_User::getUser($userID);
            if ($userPOJO == null) {
                $flashMessenger->addMessage('This ID does not exist');
                $this->redirect('/admin/user/index');
            }
            $this->view->userPOJO = $userPOJO;
        }

        $userTypePOJOs = Application_Model_UserType::getUserTypes(true);
        $this->view->userTypePOJOs = $userTypePOJOs;

        $this->render('add');
    }

    /**
     * @return void
     */
    public function confirmAction()
    {
        /** @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/user/index');
        }

        $userIDs = $this->_request->getParam('userIDs');
        if (!Application_Model_User::confirmUsers($userIDs)) {
            $flashMessenger->addMessage('Confirm Fail');
        } else {
            $var = '';

            $length = count($userIDs);
            for ($i = 0; $i < $length - 1; $i++) {
                $var .= $userIDs[$i] . ', ';
            }
            $var .= $userIDs[$length - 1];

            $flashMessenger->addMessage("Confirm $var Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * @return void
     */
    public function unconfirmAction()
    {
        /** @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/user/index');
        }

        $userID = $this->_request->getParam('userID');
        if (!Application_Model_User::unconfirmUser($userID)) {
            $flashMessenger->addMessage('Unconfirm Fail');
        } else {
            $flashMessenger->addMessage("Unconfirm $userID Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * @return void
     */
    public function unblockAction()
    {
        /** @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/user/index');
        }

        $userIDs = $this->_request->getParam('userIDs');
        if (!Application_Model_User::unblockUsers($userIDs)) {
            $flashMessenger->addMessage('Unblock Fail');
        } else {
            $var = '';

            $length = count($userIDs);
            for ($i = 0; $i < $length - 1; $i++) {
                $var .= $userIDs[$i] . ', ';
            }
            $var .= $userIDs[$length - 1];

            $flashMessenger->addMessage("Unblock $var Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }

    /**
     * @return void
     */
    public function blockAction()
    {
        /** @var $flashMessenger Zend_Controller_Action_Helper_FlashMessenger */
        $flashMessenger = $this->_helper->getHelper('FlashMessenger');

        $isPost = $this->_request->getParam('isPost');
        if (!isset($isPost)) {
            $flashMessenger->addMessage('Cannot Execute This URL Directly');
            $this->redirect('/admin/user/index');
        }

        $userIDs = $this->_request->getParam('userIDs');
        if (!Application_Model_User::blockUsers($userIDs)) {
            $flashMessenger->addMessage('Block Fail');
        } else {
            $var = '';

            $length = count($userIDs);
            for ($i = 0; $i < $length - 1; $i++) {
                $var .= $userIDs[$i] . ', ';
            }
            $var .= $userIDs[$length - 1];

            $flashMessenger->addMessage("Block $var Successfully");
        }

        $this->redirect($_SERVER['HTTP_REFERER']);
    }
}
